package com.example.a7822.myapplication.shopcart.view;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.a7822.myapplication.Constant;
import com.example.a7822.myapplication.R;
import com.example.a7822.myapplication.shopcart.SPCartManager;
import com.example.a7822.myapplication.shopcart.beans.GoodBean;
import com.example.a7822.myapplication.utils.CommonUtil;
import com.example.a7822.myapplication.utils.Logger;
import com.github.chrisbanes.photoview.PhotoView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by asus on 2017/7/11.
 */

public class CartAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    public static final String TAG = Constant.TAG;
//    public static final int TYPE_HEADER = 0;//带有Header
    public static final int TYPE_FOOTER = 1;//带有Footer
    public static final int TYPE_NORMAL = 2;//不带header和footer

    List<GoodBean> dataList = new ArrayList<GoodBean>();
    private Logger logger = Logger.getLogger(CartAdapter.class);
    private Context context;

    private OnDeleteClickListener mOnDeleteClickListener;
    private OnEditClickListener mOnEditClickListener;
    private OnResfreshListener mOnResfreshListener;
    private boolean isEditing = false;

    public CartAdapter(List list){
        dataList = list;
    }
    public CartAdapter(Context ctx){
        context = ctx;
    }
    public CartAdapter(Context ctx,List list){
        context = ctx;
        dataList = list;
    }

    public void refreshData(){

        dataList = SPCartManager.getInstance().getGoodList();

        notifyDataSetChanged();

//        context.updateInfo();
    }



    /** 重写这个方法，很重要，是加入Header和Footer的关键，我们通过判断item的类型，从而绑定不同的view    * */
    @Override
    public int getItemViewType(int position) {
     /*   if (position == 0){
            //第一个item应该加载Header
            return TYPE_HEADER;
        }*/
//        if (position == getItemCount()-1){
//            //最后一个,应该加载Footer
//            return TYPE_FOOTER;
//        }
        return TYPE_NORMAL;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v;

        /*if (viewType == TYPE_FOOTER){
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sp_footer,parent,false);
            FooterViewHolder vh = new FooterViewHolder(v);

            return vh;
        }*/
       /* if (viewType == TYPE_HEADER){
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sp_header,parent,false);
            HeaderViewHolder vh = new HeaderViewHolder(v);

            return vh;
        }*/

        v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart,parent,false);
        NormalViewHolder vh = new NormalViewHolder(v);

        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        try {
            if (holder instanceof NormalViewHolder) {
                NormalViewHolder vh = (NormalViewHolder) holder;

                //这里加载数据的时候要注意，是从position-1开始，因为position==0已经被header占用了
                vh.goodName.setText(CommonUtil.getLimitString(dataList.get(position).getGoodName(),12));
                vh.goodDesc.setText(CommonUtil.getLimitString(dataList.get(position).getGoodDesc(),24));
                vh.goods_price.setText(String.valueOf("¥"+dataList.get(position).getGoodPriceNow()));
//                vh.market_price.setText(String.valueOf(dataList.get(position).getGoodPriceBefore()));
                vh.goods_num_real.setText(String.valueOf(dataList.get(position).getGoodAmount()));
//                vh.goodImage.setI(dataList.get(position).getGoodPic());
                Picasso.with(context)
                        .load(dataList.get(position).getGoodPic())
                        .into(vh.goodImage);

                if (isEditing){
                    if (dataList.get(position).isSelected()){
                        vh.act_select.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.shopcart_selected));

                    }else{
                        vh.act_select.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.shopcart_unselected));
                    }
                    vh.act_select.setVisibility(View.VISIBLE);

                }else{
                    vh.act_select.setVisibility(View.GONE);
                }





                vh.bindView(position);
            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public void deleteItems() {

        //获取需要删除的商品位置
        ArrayList<Integer> deleteIDs = new ArrayList();
        for (int i=0;i < dataList.size() ; i++){
            GoodBean good = dataList.get(i);
            if (good.isSelected()){
                deleteIDs.add(i);
            }
        }
        //删除
        Collections.sort(deleteIDs, Collections.reverseOrder());//降序排列所有需要删除的ID
        for (int j : deleteIDs){
            dataList.remove(j);
        }




        notifyDataSetChanged();
    }

    public void setIsEditing(boolean isEditing) {
        this.isEditing = isEditing;
        notifyDataSetChanged();
    }


    public class FooterViewHolder extends ViewHolder {

//        @BindView(R.id.more_data_msg) TextView more_data_msg;

        public FooterViewHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this,itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the item
                    Log.d(TAG,"footer onClick.");
                }
            });
        }
    }

    // Now define the viewholder for Normal list item
    public class NormalViewHolder extends ViewHolder {

        @BindView(R.id.add_goods)
        ImageView act_add;
        @BindView(R.id.tv_item_shopcart_clothselect)
        ImageView act_select;
        @BindView(R.id.minus_goods)
        ImageView act_minus;
//        @BindView(R.id.delete_goods) ImageView act_delete;
        @BindView(R.id.goods_image) PhotoView goodImage;
        @BindView(R.id.goods_name) TextView goodName;
        @BindView(R.id.goods_desc)
        TextView goodDesc;
        @BindView(R.id.goods_num_real)
        TextView goods_num_real;
        @BindView(R.id.goods_price)
        TextView goods_price;
//        @BindView(R.id.market_price) TextView market_price;

        public NormalViewHolder(final View itemView) {


            super(itemView);

            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the normal items
                    Log.d(TAG,"item "+goodName.getText() + " onClick.");
                }
            });

        }

        @Override
        public void bindView(final int position) {
            super.bindView(position);
            //监听是否应该全选
            if(mOnResfreshListener != null){
                boolean isAllSelect = false;
                boolean isOneSelect = false;
                for(int i = 0;i < dataList.size(); i++){
                    if(!dataList.get(i).isSelected()){
                        isAllSelect = false;
                        break;
                    }else{
                        isAllSelect = true;
                    }
                }
                for(int i = 0;i < dataList.size(); i++){
                    if(dataList.get(i).isSelected()){
                        isOneSelect = true;
                        break;
                    }
                }

                mOnResfreshListener.onResfresh(isAllSelect,isOneSelect);
            }
            //增加数量
            act_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int newCount = dataList.get(position).getGoodAmount() + 1 ;


                    dataList.get(position).setGoodAmount(newCount);

                    if(mOnEditClickListener != null){
                        mOnEditClickListener.onEditClick(position,dataList.get(position).getGoodId(),newCount);
                    }
                    //同步数据
                    SPCartManager.getInstance().setGoodPrice(dataList.get(position).getGoodId());
                    goods_num_real.setText(String.valueOf(newCount));

                    logger.d("修改商品"+dataList.get(position).getGoodName()+ "的数量为："+newCount);
//                    notifyDataSetChanged();
//                    context.updateInfo();

                }
            });
            //减少数量
            act_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dataList.get(position).getGoodAmount() <= 1) return;

                    int newCount = dataList.get(position).getGoodAmount()-1;
                    dataList.get(position).setGoodAmount(newCount);

                    if(mOnEditClickListener != null){
                        mOnEditClickListener.onEditClick(position,dataList.get(position).getGoodId(),newCount);
                    }

                    //同步数据
                    SPCartManager.getInstance().setGoodPrice(dataList.get(position).getGoodId());
                    goods_num_real.setText(String.valueOf(newCount));

                    logger.d("修改商品"+dataList.get(position).getGoodName()+ "的数量为："+newCount);
//                    notifyDataSetChanged();
//                    context.updateInfo();
                }
            });
            //删除商品
           /* act_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog(v,position);
                }
            });*/

            act_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isSelect = !dataList.get(position).isSelected();

                    if (isSelect){
                        act_select.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.shopcart_selected));

                    }else{
                        act_select.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.shopcart_unselected));
                    }
                    dataList.get(position).setSelected(isSelect);

                    notifyDataSetChanged();
//                    mOnResfreshListener.onResfresh(isSelect);
                }
            });
        }
    }
    private void showDialog(final View view, final int position){


    }

    public class HeaderViewHolder extends RecyclerView.ViewHolder {

//        @BindView(R.id.header) ImageView header;

        public HeaderViewHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this,itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the item
//                    Toast.makeText(get,"我是header",Toast.LENGTH_SHORT).show();
                    Log.d(TAG,"header onClick.");
                }
            });
        }
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        // Define elements of a row here


        public ViewHolder(View itemView) {
            super(itemView);

            // Find view by ID and initialize here
        }

        public void bindView(int position) {
            // bindView() method to implement actions
        }




    }

    public interface OnDeleteClickListener{
        void onDeleteClick(View view, int position, int cartid);
    }

    public void setOnDeleteClickListener(OnDeleteClickListener mOnDeleteClickListener){
        this.mOnDeleteClickListener = mOnDeleteClickListener;
    }
    public interface OnEditClickListener{
        void onEditClick(int position, int cartid, int count);
    }

    public void setOnEditClickListener(OnEditClickListener mOnEditClickListener){
        this.mOnEditClickListener = mOnEditClickListener;
    }

    public interface OnResfreshListener{
        void onResfresh(boolean isAllSelect, boolean isOneSelect);
    }

    public void setResfreshListener(OnResfreshListener mOnResfreshListener){
        this.mOnResfreshListener = mOnResfreshListener;
    }
}
